﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Web;
using Orchard.Data;

namespace Amba.ULogin.Services
{
    public interface ISettingsService<T>
    {
        void Save();
        T Settings { get; }

    }

    public abstract class SettingsService<T> : ISettingsService<T> 
        where T: class, new()
    {
        private readonly IRepository<T> _repo;
        private T _settings;
        private static readonly object _syncRoot = new object();

        public SettingsService(IRepository<T> repo)
        {
            _repo = repo;

            lock (_syncRoot)
            {
                _settings = _repo.Table.FirstOrDefault();
                if (_settings == null)
                {
                    _settings = GetDefaultSettings();
                    _repo.Create(_settings);
                }
            }
        }

        public virtual T GetDefaultSettings()
        {
            return new T();
        }

        public void Save()
        {
            _repo.Update(_settings);
        }

        public T Settings
        {
            get { return _settings; }
        }
    }
}